<template>
  <div class="search">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.go(-1)"></van-nav-bar>

    <!-- 搜索框 -->
    <!-- https://youzan.github.io/vant/#/zh-CN/search -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="suggest"
      @focus="isFocus = true"
      @blur="isFocus = false"
    >
      <template #action>
        <div @click="search(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group v-if="keyword">
      <van-cell icon="search" v-for="(item, index) in showList" :key="index">
        <template #title>
          <div v-html="item" @click="search(suggestList[index])"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录">
      </van-cell>
      <van-cell @click="search(item)" :title="item" v-for="(item, index) in historyList" :key="index">
        <van-icon name="close" @click="del(index)" />
      </van-cell>
    </van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { suggestArticle } from '@/api/article'
import { setHistory, getHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      // 推荐的数组
      suggestList: [],
      // 搜索的历史记录
      historyList: getHistory(),
      isFocus: false
    }
  },
  computed: {
    showList () {
      // 高亮的数组，用于显示
      return this.suggestList.map(item => {
        // 对item进行高亮处理
        const reg = new RegExp(this.keyword, 'gi')
        return item.replace(reg, match => `<span style="color: red;">${match}</span>`)
      })
    }
  },
  methods: {
    suggest () {
      // 发送ajax请求
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.keyword) return
        const res = await suggestArticle(this.keyword)
        console.log(res)
        this.suggestList = res.data.options
      }, 500)
    },
    search (key) {
      // console.log(key, '搜索')
      // 不允许有重复的搜索记录
      this.historyList = this.historyList.filter(item => item !== key)
      this.historyList.unshift(key)
      // 把历史记录保存localStorage中
      setHistory(this.historyList)
      // 跳转到搜索结果页面
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: key
        }
      })
    },
    del (index) {
      this.historyList.splice(index, 1)
      setHistory(this.historyList)
    }
  }
}
</script>

<style></style>
